package com.dmai.capacity.platform.common.model;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import lombok.EqualsAndHashCode;
import org.apache.commons.collections4.collection.SynchronizedCollection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.Data;

/**
 * 用户实体绑定spring security
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class LoginAppUser extends BaseUser implements SocialUserDetails {
	
	private static final long serialVersionUID = -3685249101751401211L;

	private String tenantId;

	private String roleIds;

	private Set<SysRole> roles;

	private Set<String> permissions;

	/***
	 * 权限重写
	 */
	@JsonIgnore
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> collection = SynchronizedCollection.synchronizedCollection(new HashSet<>());
		 if (!CollectionUtils.isEmpty(roles)) {
			 roles.parallelStream()
					.forEach(role -> collection.add(new SimpleGrantedAuthority(role.getCode())));
		 }
//		collection.add(new SimpleGrantedAuthority("all"));
		return collection;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return getEnabled();
	}

	public void setEnabled(boolean flag) {
		super.setEnabled(flag);
	}

	@Override
	public String getUserId() {
		return super.getId().toString();
	}
}
